﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

using PetaPoco;
using Marking.Dashboard.Web.DataContracts;
using Marking.Dashboard.Web.ServiceContracts;

namespace Marking.Dashboard.Web.Services
{
    public class SalesService : ISalesService
    {
        public IEnumerable<SalesDTO> LoadSalesInfos(string cycleType, DateTime startDate, DateTime endDate)
        {
            var db = this.CreateDb();
            db.EnableAutoSelect = false;

            var maps = new Dictionary<string, string>
            {
                { "年", "year"},
                { "月", "month"},
                { "日", "day"}
            };

            if (maps.ContainsKey(cycleType))
            {
                cycleType = maps[cycleType];
            }

            var results = db
                .Query<ReportSellAllDataResult>("EXEC [Pro_ReportSellAllData] @0, @1, @2", startDate, endDate, cycleType)
                .OrderBy(x=>x.StartDate).ToList();

            return this.CreateSalesInfos(results);
        }

        private Database CreateDb()
        {
            return new Database("Marking");
        }

        private IEnumerable<SalesDTO> CreateSalesInfos(IEnumerable<ReportSellAllDataResult> results)
        {
            var stockQuantities =
                (from item in results
                 select new SalesDTO
                 {
                     StartDate = item.StartDate,
                     EndDate = item.EndDate,
                     Quantity = item.SellCount ?? 0
                 }).ToList();

            return stockQuantities;
        }

        private class ReportSellAllDataResult
        {
            public DateTime StartDate { get; set; }
            public DateTime EndDate { get; set; }
            public decimal? SellCount { get; set; }
            public decimal? SellMoney { get; set; }
        }
    }
}